const { Op } = require("sequelize");

const goodModel = appRequire('models/good');
const sequelize = appRequire('db');

// 导出对象，供其它模块调用
module.exports = {
    list,
    save,
    destroy,
};

async function list(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, [], request);
    if (checkResult == false) return;

    let params = {}

    let thisOrder = ["createdAt", 'ASC']
    if (postData.goodsClass) params.goodClassId = postData.goodsClass
    if (postData.searchText) {
        params[Op.or] = [
            { goodsName: { [Op.like]: '%' + postData.searchText + '%' } },
            { goodsName: sequelize.where(sequelize.fn('LOWER', sequelize.col('headerGood.goodsName')), 'LIKE', '%' + postData.searchText + '%') },
            // { models: { [Op.substring]: postData.searchText } },
        ]
    }
    if (postData.order) {
        if (postData.order.indexOf("-") != -1) thisOrder = [postData.order.split("-")[1], 'DESC']
        else thisOrder = [postData.order, 'ASC']
    }
    let good = await goodModel.good.findAll({
        where: params,
        order: [thisOrder],
    })
    good = Common.clone(good)

    returnData.data = good
    request.json(returnData)
}

async function save(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['subGoodIcons', 'goodsName'], request);
    if (checkResult == false) return;

    let params = {
        goodClassId: postData.goodClassId,
        goodsName: postData.goodsName,
        isNice: postData.isNice,
        maxPrice: Number(postData.maxPrice),
        minPrice: Number(postData.minPrice),
        productId: postData.productId,
        status: postData.status,
        subGoodIcons: postData.subGoodIcons,
        tags: postData.tags
    }
    if (postData.objectId) {
        let result = await goodModel.good.update(params, {
            where: {
                objectId: postData.objectId
            }
        })
        returnData.data = result
    } else {
        params.objectId = sid.uuid()
        let result = await goodModel.good.create(params)
        returnData.data = result
    }

    request.json(returnData)
}

async function destroy(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, ['objectId'], request);
    if (checkResult == false) return;

    let result = await goodModel.good.destroy({
        where: {
            objectId: postData.objectId
        }
    })
    returnData.data = result
    request.json(returnData)
}
